﻿using System;
using System.Web;
using Microsoft.SharePoint;

namespace RSPDS.Core
{
    public static class RSPDS_Webs
    {
        public static void OpenWeb(string url, Action<SPSite, SPWeb> del)
        {
            if (null == del) throw new ArgumentNullException("del");
            RSPDS_Sites.OpenSite(url, site =>
            {
                using (var web = site.OpenWeb())
                {
                    del(site, web);
                }
            });
        }

        public static void OpenWeb(Guid siteId, Guid webId, Action<SPSite, SPWeb> del)
        {
            if (Guid.Empty == webId) throw new ArgumentNullException("webId");
            if (null == del) throw new ArgumentNullException("del");
            RSPDS_Sites.OpenSite(siteId, site =>
            {
                using (var web = site.AllWebs[webId])
                {
                    del(site, web);
                }
            });
        }

        public static void CurrentWeb(Action<SPSite, SPWeb> del)
        {
            if (null == del) throw new ArgumentNullException("del");
            if (null != SPContext.Current)
            {
                using (var site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (var web = site.AllWebs[SPContext.Current.Web.ID])
                    {
                        del(site, web);
                    }
                }
            }
            else if (null != HttpContext.Current)
            {
                using (var site = new SPSite(HttpContext.Current.Request.Url.ToString()))
                {
                    using (var web = site.OpenWeb())
                    {
                        del(site, web);
                    }
                }
            }
            else
            {
                throw new RSPDS_CoreException("SPContext and HttpContext is null");
            }
        }

        public static void OpenElevatedWeb(string url, Action<SPSite, SPWeb> del)
        {
            SPSecurity.RunWithElevatedPrivileges(() => OpenWeb(url, del));
        }

        public static void OpenElevatedWeb(Guid siteId, Guid webId, Action<SPSite, SPWeb> del)
        {
            SPSecurity.RunWithElevatedPrivileges(() => OpenWeb(siteId, webId, del));
        }
    }
}
